package com.sright.bcard.component.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.sright.bcard.common.service.share.constants.RedisKeyConstants;
import com.sright.bcard.common.service.share.dto.component.ComponentConfigWhiteListDTO;
import com.sright.bcard.common.service.share.okhttp.serial.SerialUtil;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.JedisUtil;
import com.sright.bcard.component.biz.manager.ComponentConfigWhiteListManager;
import com.sright.bcard.component.dal.dao.ComponentConfigWhiteListDAO;
import com.sright.bcard.component.dal.entity.ComponentConfigWhiteListDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ComponentConfigWhiteListManagerImpl implements ComponentConfigWhiteListManager {

    @Autowired
    private ComponentConfigWhiteListDAO componentConfigWhiteListDAO;

    @Autowired
    private JedisUtil jedisUtil;

    @Override
    public ComponentConfigWhiteListDTO getComponentConfigWhiteListByEnterprise(Long enterpriseId) {
        // 从缓存中获取数据
        String json = jedisUtil.get(RedisKeyConstants.COMPONENT_WHITE_LIST + enterpriseId);
        if(StringUtils.isEmpty(json)) {
            // 根据企业id查询白名单
            ComponentConfigWhiteListDO componentConfigWhiteListDO = componentConfigWhiteListDAO.selectByEnterpriseId(enterpriseId);
            if(null != componentConfigWhiteListDO) {
                jedisUtil.setExpire(RedisKeyConstants.COMPONENT_WHITE_LIST + enterpriseId, JSON.toJSONString(componentConfigWhiteListDO), 3600);
                ComponentConfigWhiteListDTO componentConfigWhiteListDTO = DataConvertUtils.convertDO2DTO(componentConfigWhiteListDO, ComponentConfigWhiteListDTO.class);
                return componentConfigWhiteListDTO;
            } else {
                return null;
            }
        }
        return SerialUtil.json2Object(json, ComponentConfigWhiteListDTO.class);
    }
}
